package com.feng.security.dsa.comon;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.commons.codec.binary.Base64;

public class DSAKeyMan {

	/**
	 * 生成DSA密钥
	 * 
	 * @return
	 */
	public SignatureResult genDSAKeyPair() {
		return this.genDSAKeyPair(new Integer(1024));
	}

	/**
	 * 生成DSA密钥
	 * 
	 * @param length
	 *            密钥长度，必须大于等于1024
	 * @return
	 */
	public SignatureResult genDSAKeyPair(Integer length) {
		SignatureResult rt = new SignatureResult();
		try {
			if (length.intValue() < 1024) {
				rt.setSuccess(false);
				rt.setErrorMessage(SignErrorMessage.ILLEAGL_PARAMETER);
				return rt;
			}
			KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
			SecureRandom sr = new SecureRandom();
			sr.setSeed(System.currentTimeMillis());
			keygen.initialize(length.intValue(), sr);
			KeyPair keyPair = keygen.generateKeyPair();
			rt.setPrivateKey(new String(Base64.encodeBase64(keyPair
					.getPrivate().getEncoded(), true)));
			rt.setPublicKey(new String(Base64.encodeBase64(keyPair.getPublic()
					.getEncoded(), true)));
			rt.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			rt.setErrorMessage(SignErrorMessage.SYSTEM_ERROR + e.getMessage());
		}
		return rt;
	}

	/**
	 * 根据String获得DSA私钥
	 * 
	 * @param keyBase64Encode
	 *            经过"new String(Base64.encodeBase64(key.getEncoded()))"构造的String
	 * @return
	 */
	public PrivateKey getPKCS8PrivateKey(String keyBase64Encode) {
		PrivateKey privkey = null;
		try {
			KeyFactory keyFac = KeyFactory.getInstance("DSA");
			byte[] keyEncode = Base64.decodeBase64(keyBase64Encode.getBytes());
			// PrivateKey的Encode为PKCS8，通过PrivateKey.getFormat()可以验证
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyEncode);
			privkey = keyFac.generatePrivate(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return privkey;
	}

	/**
	 * 根据String获得DSA公钥
	 * 
	 * @param keyBase64Encode
	 *            经过"new String(Base64.encodeBase64(key.getEncoded()))"构造的String
	 * @return
	 */
	public PublicKey getX509PublicKey(String keyBase64Encode) {
		PublicKey pubkey = null;
		try {
			KeyFactory keyFac = KeyFactory.getInstance("DSA");
			byte[] keyEncode = Base64.decodeBase64(keyBase64Encode.getBytes());
			// PublicKey的Encode为X509，通过PublicKey.getFormat()可以验证
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyEncode);
			pubkey = keyFac.generatePublic(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pubkey;
	}
}
